package server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: liuchong
 * @create: 2023/2/22 16:31
 * @description:
 */
public class QuotationServerSingle extends ServerSocket {
    private static final int SERVER_PORT = 8899; // 服务端端口
    private Socket socket;

    private InputStreamReader inputStreamReader;

    private FileOutputStream fos;
    private final String PATTERN_ID = "(?<=id\\=)\\s*\\d*[1-9]";
    private final String PATTERN_BID = "(?<=bid\\=)\\s*\\d*[1-9]";
    private final String PATTERN_ASK = "(?<=ask\\=)\\s*\\d*[1-9]";

    public QuotationServerSingle() throws Exception {
        super(SERVER_PORT);
    }

    /**
     * 使用线程处理每个客户端传输的文件
     * @throws Exception
     */
    public void load() throws Exception {
        while (true) {
            // server尝试接收其他Socket的连接请求，server的accept方法是阻塞式的
            Socket socket = this.accept();
            String fileName = "quotation_data.txt";
            String fileLogName = "log.txt";
            Pattern rId = Pattern.compile(PATTERN_ID);
            Pattern rBid = Pattern.compile(PATTERN_BID);
            Pattern rAsk = Pattern.compile(PATTERN_ASK);
            File directory = new File("output");
            if(!directory.exists()) {
                directory.mkdir();
            }
            File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
            File fileLog = new File(directory.getAbsolutePath() + File.separatorChar + fileLogName);
            BufferedWriter bw = null;
            BufferedWriter bwLog = null;

            try {
                bw = new BufferedWriter(new FileWriter(file, true));
                bwLog = new BufferedWriter(new FileWriter(fileLog));
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                long startTime = System.currentTimeMillis();
                inputStreamReader = new InputStreamReader(socket.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                // 每行读取的数据
                String s = "";
                List<String> rightList = new ArrayList<>();
                List<String> wrongList = new ArrayList<>();
                while ((s = bufferedReader.readLine()) != null) {
                    Matcher mId = rId.matcher(s);
                    Matcher mBid = rBid.matcher(s);
                    Matcher mAsk = rAsk.matcher(s);
                    if (s.length() != 0 && mId.find() && mBid.find() && mAsk.find()) {
                        rightList.add(s);
                    }
                    else {
                        wrongList.add(s);
                    }
                }
                Collections.sort(rightList, new StringComparator());

                for (String sortedMes: rightList) {
                    bw.write(sortedMes);
                    bw.newLine();
                    bw.flush();
                }
                for (String wrongMes: wrongList) {
                    bwLog.write(wrongMes);
                    bwLog.newLine();
                    bwLog.flush();

                }
                System.out.println("======== 文件接收成功 [File Name：" + fileName + "]  ========");
                long endTime = System.currentTimeMillis();
                System.out.println("程序运行时间： " + (endTime - startTime) + "ms");
            } catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                try {
                    if (bw != null)
                        bw.close();
                    if (bwLog != null)
                        bwLog.close();
                    socket.close();


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class StringComparator implements Comparator<String> {
        @Override
        public int compare(String s1, String s2) {
            return s1.substring(s1.length() - 13).compareTo(s2.substring(s2.length() - 13));
        }
    }

    /**
     * 入口
     * @param args
     */
    public static void main(String[] args) {
        try {
            QuotationServerSingle server = new QuotationServerSingle(); // 启动服务端
            server.load();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
